//
//  oldVideoView.m
//  laonianbangfamily
//
//  Created by 勇拓 李 on 18/3/30.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldVideoView.h"
#import <AVFoundation/AVFoundation.h>

#define PLAY_IMG [UIImage imageNamed:@"播放小"]
#define STOP_IMG [UIImage imageNamed:@"暂停"]

@interface oldVideoView()
{
    NSDateFormatter *_dateFormatter;
}

@property (nonatomic ,strong) AVPlayer *player;
@property (nonatomic ,strong) AVPlayerItem *playerItem;
@property (nonatomic ,strong) id playbackTimeObserver;

@property (weak, nonatomic) IBOutlet UISlider *slider_view;
@property (weak, nonatomic) IBOutlet UIButton *btn_center_play;
@property (weak, nonatomic) IBOutlet UIButton *btn_play;
@property (weak, nonatomic) IBOutlet UIProgressView *progress_view;
@property (weak, nonatomic) IBOutlet UIView *playerView;
@property (weak, nonatomic) IBOutlet UILabel *label_time;
@property (strong, nonatomic)UIActivityIndicatorView *hud;
@property (strong, nonatomic)UIImageView *fristImg;

@property (nonatomic, assign)oldVideoType type;
@property (nonatomic, assign)oldVideoFillType fillType;
@property (nonatomic, copy)NSString *url;
@property (assign, nonatomic) BOOL played;
@property (assign, nonatomic)BOOL notFirstPlay;
@property (nonatomic, strong)NSString *totalTime;
@end

@implementation oldVideoView

- (instancetype)initByType:(oldVideoType)type url:(NSString *)url fillType:(oldVideoFillType)filtype
{
    self = [[[NSBundle mainBundle] loadNibNamed:@"oldVideoView"
                                          owner:self
                                        options:nil] objectAtIndex:0];;
    if (self) {
        self.type = type;
        self.url = url;
        self.fillType = filtype;
        [self initView];
    }
    
    return self;
}

- (void)initView
{
    UIImage *thumbImageNormal = [UIImage imageNamed:@"指示器"];
    
    [_slider_view setThumbImage:thumbImageNormal forState:UIControlStateNormal];
    
    
    //设置thumb 按住高亮时的图片
    UIImage *thumbImageHighlighted = [UIImage imageNamed:@"指示器"];
    
    [_slider_view setThumbImage:thumbImageHighlighted forState:UIControlStateHighlighted];
    
    _btn_center_play.hidden = NO;
    [_btn_center_play addTarget:self action:@selector(btn_center_touched:) forControlEvents:UIControlEventTouchDown];
    
    [_btn_play addTarget:self action:@selector(btn_play_touched:) forControlEvents:UIControlEventTouchDown];
    //    _btn_play.enabled = NO;
    
    _playerView.userInteractionEnabled = YES;
    UITapGestureRecognizer* tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoFullScrenn:)];
    [_playerView addGestureRecognizer:tapGes];
}

- (void)initPlayer
{
    NSURL *videoUrl = nil;
    
    if (VideoWeb == _type) {
        videoUrl = [NSURL URLWithString:_url];
    }
    else
    {
        videoUrl = [NSURL fileURLWithPath:_url];
    }
    
    //@"http://sxw-sxt-resouces.oss-cn-hangzhou.aliyuncs.com/dtrp/video/001fe8c4e3f24b11b44a1d7b01a0bdb5.mp4"
    
    _playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    
    [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    [_playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
    
    _player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = _playerView.bounds;
    if (_fillType == VideoAspect) {
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;//视频填充模式
    }
    else
    {
        playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;//视频填充模式
    }
    
    [_playerView.layer addSublayer:playerLayer];
    
//    _playerView.player = _player;
    
    if (VideoWeb == _type) {
        _hud = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
        _hud.center = _playerView.center;
        [_hud setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [_hud setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [_hud setBackgroundColor:[UIColor clearColor]];
        [_playerView addSubview:_hud];
        [_hud startAnimating];
    }
}

- (void)dealloc {
    [_playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [_playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    [_player removeTimeObserver:self.playbackTimeObserver];
}


- (void)btn_play_touched:(id)sender
{
    if (!_played) {
        [self playFuc];
    } else {
        [_player pause];
        [_btn_play setImage:PLAY_IMG forState:UIControlStateNormal];
        _btn_center_play.hidden = NO;
        
        if ([_hud superview]) {
            [_hud stopAnimating];
        }
    }
    _played = !_played;
}

- (void)btn_center_touched:(id)sender
{
    if (!_played) {
        [self playFuc];
    }
    _played = !_played;
}


- (void)playFuc
{
    if (!_notFirstPlay) {
        _notFirstPlay = YES;
        [self initPlayer];
    }
    [_player play];
    [_btn_play setImage:STOP_IMG forState:UIControlStateNormal];
    _btn_center_play.hidden = YES;
    if ([_hud superview]) {
        [_hud startAnimating];
    }
    if (_fristImg.superview) {
        [_fristImg removeFromSuperview];
    }
}

- (void)gotoFullScrenn:(id)sender
{
    if (self.delegate) {
        //暂停当前的播放
        _played = YES;
        [self btn_play_touched:nil];
        
        [self.delegate touchedFullScreen:_url type:_type];
    }
}

#pragma mark -其它

- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    __weak typeof(self) weakSelf = self;
    self.playbackTimeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
        [weakSelf.slider_view setValue:currentSecond animated:YES];
        NSString *timeString = [weakSelf convertTime:currentSecond];
        weakSelf.label_time.text = [NSString stringWithFormat:@"%@/%@",timeString,weakSelf.totalTime];
    }];
}

// KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            
            if ([_hud superview]) {
                [_hud stopAnimating];
                [_hud removeFromSuperview];
            }
            
            _btn_center_play.enabled = YES;
            _btn_play.enabled = YES;
            CMTime duration = self.playerItem.duration;// 获取视频总长度
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            _totalTime = [self convertTime:totalSecond];// 转换成播放时间
            [self customVideoSlider:duration];// 自定义UISlider外观
            NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
            [self monitoringPlayback:self.playerItem];// 监听播放状态
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            
            NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        [_progress_view setProgress:timeInterval / totalDuration animated:YES];
    }
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (void)customVideoSlider:(CMTime)duration {
    _slider_view.maximumValue = CMTimeGetSeconds(duration);
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [_slider_view setMinimumTrackImage:transparentImage forState:UIControlStateNormal];
    [_slider_view setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}

- (void)updateVideoSlider:(CGFloat)currentSecond {
    [_slider_view setValue:currentSecond animated:YES];
}


- (void)moviePlayDidEnd:(NSNotification *)notification {
    NSLog(@"Play end");
    
    __weak typeof(self) weakSelf = self;
    [_player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        [weakSelf.slider_view setValue:0.0 animated:YES];
        [weakSelf.btn_play setImage:PLAY_IMG forState:UIControlStateNormal];
        _btn_center_play.hidden = NO;
        _played = NO;
    }];
}

- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}

#pragma mark -UISlider
- (IBAction)videoSlierChangeValue:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value change:%f",slider.value);
    
    if (slider.value == 0.000000) {
        __weak typeof(self) weakSelf = self;
        [_player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            [weakSelf.player play];
        }];
    }
}

- (IBAction)videoSlierChangeValueEnd:(id)sender {
    UISlider *slider = (UISlider *)sender;
    NSLog(@"value end:%f",slider.value);
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        
        [weakSelf playFuc];
    }];
}

@end
